package com.gitee.apanlh.web.wrapper;

import com.gitee.apanlh.util.encode.StrEncodeUtils;
import com.gitee.apanlh.util.io.IOUtils;
import com.gitee.apanlh.web.util.ServletUtils;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;

/**
 * 	重写HttpRequest
 * 	
 * 	@author Pan
 */
public class RefreshRequestWrapper extends HttpServletRequestWrapper {

	/** 请求体内容 */
	private byte[] requestBody;

	/**	
	 * 	构造函数-重写HTTPServletRequest请求
	 * 	<br>使用{@link #getBody()}获取请求体内容
	 * 	<br>不会关闭HttpServletRequest中的读取输入流
	 * 	
	 * 	@author Pan
	 * 	@param 	request	HttpServletRequest
	 */
	public RefreshRequestWrapper(HttpServletRequest request) {
		super(request);
		this.requestBody = IOUtils.read(ServletUtils.getInputStream(request), false);
	}

	@Override
	public ServletInputStream getInputStream() {
		final ByteArrayInputStream bais = new ByteArrayInputStream(this.requestBody);
		
		return new ServletInputStream() {
			@Override
			public boolean isFinished() {
				return false;
			}
			@Override
			public boolean isReady() {
				return false;
			}
			@Override
			public void setReadListener(ReadListener readListener) {
				//	无效
			}
			@Override
			public int read() {
				return bais.read();
			}
		};
	}

	@Override
	public BufferedReader getReader() {
		return IOUtils.getReaderUtf8(getInputStream());
	}
	
	/**	
	 * 	获取请求体
	 * 	
	 * 	@author Pan
	 * 	@return	String
	 */
	public String getBody() {
		return StrEncodeUtils.utf8EncodeToStr(this.requestBody);
	}
}
